'''
File: functions.py
Author: Nathan Hoad
Description: Misc. functions used in makeme.
'''
import logging
import sys
import time
import os
import math
import datetime
import configparser

from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE


def encrypt(key, msg):
    """Simple encryption so passwords aren't stored in plain-text.

    Please note that this is quite weak security, and completely breakable
    with little or no effort. If you take issue with this method, don't
    hesitate to offer your own implementation. I know very little about
    security and would be happy for someone to school me on this.

    Keyword arguments:
    key -- the key to use for encryption. Supa-secret!
    msg -- the text to be encrypted.

    Returns msg in encrypted form.

    """
    enc = []

    for i, c in enumerate(msg):
        key_c = ord(key[i % len(key)])
        msg_c = ord(c)
        enc.append(chr((msg_c + key_c) % 127))

    return ''.join(enc)


def decrypt(key, enc):
    """Simple decryption. Reverse of the encryption function

    Please note that this is quite weak security, and completely breakable
    with little or no effort. If you take issue with this method, don't
    hesitate to offer your own implementation. I know very little about
    security and would be happy for someone to school me on this.

    Keyword arguments:
    key -- the key to use for encryption. Supa-secret!
    msg -- the text to be decrypted.

    Returns enc in decrypted form.

    """
    msg = []

    for i, c in enumerate(enc):
        key_c = ord(key[i % len(key)])
        msg_c = ord(c)
        msg.append(chr((msg_c - key_c) % 127))

    return ''.join(msg)


def save_emails_to_file(emails, filename, reason):
    """Save a list of emails to a file in the current working directory.

    Keyword arguments:
    emails -- list of Email objects to be saved to file.
    filename -- the filename to save unsent emails to.
    reason -- the text or exception reason the emails couldn't be sent.

    """
    now = datetime.datetime.now()
    date = '{0}-{1}-{2}'.format(now.day, now.month, now.year)
    time = '{0}:{1}:{2}'.format(now.hour, now.minute, now.second)
    with open(filename, 'a') as f:
        f.write('On the {0}, at {1}, the following emails could not be sent:\n'.format(date, time))
        f.write('The reason for this: {0}\n'.format(reason))

        for e in emails:
            f.write('{0}\n'.format(e))
